<?php 
namespace XFCore\controllers\user;
use lib\{BaseController , XFCaptcha , Examine};
use lib\protocol\{cookie,QQweb,WxMac,WxUos,WxIpad,QQPC};
use XFCore\traits\UserTraits;
class AjaxController extends BaseController{
    use UserTraits;
    protected $XFCaptcha;
    protected $cookie;
    protected $QQweb;
    protected $QQPC;
    public function __construct(){
       parent::__construct();
       $this->XFCaptcha = new XFCaptcha(CaptchaCode);
       $this->cookie = new cookie();
       $this->QQweb  = new QQweb();
       $this->QQPC  = new QQPC($this->qqprotocol['qqpc']);
    }
    
    public function login(){
        if($this->islogin_user == 1 )exitjson(-1,"您已登录");
        if(!$this->XFCaptcha->XYcaptcha($this->input->img_code))exitjson(-1,'验证码为空或错误！');
        $user = $this->input->username;
        $pwd  = $this->input->password;
        if(empty($user) || empty($pwd))exitjson(-1,'账号和密码不可为空！');
        $data = ['user', 'email', 'phone'];
        $conditions = [];
        $params = [];
        
        foreach ($data as $key) {
            $conditions[] = "`$key` = :user";
        }
        $sql = "SELECT * FROM `pre_user` WHERE " . implode(' OR ', $conditions) . " LIMIT 1";
        $params = ['user' => $user];
        $userrow = safeSqlQuery($sql, $params,'select',['single_row'=>true])['result'];
        if(empty($userrow)){
            exitjson(-1,'账号或密码错误！');
        }
        $usernum =  $this->db->usernum($userrow['pid'] , http_ip());
        
        if($usernum >= userloginnum ){
             exitjson(-1,'您多次尝试登录但登录失败 已被禁止登录');
        }
        $salt = $userrow['salt'];
        $password = md5($salt . md5($salt.$pwd.$salt.md5($salt.$pwd.$salt).$pwd.$salt) . $salt);
        if($password !== $userrow['pass']){
            createLog('尝试登录用户中心但密码错误-提交的密码为:'.$pwd,http_ip(),$userrow['user']);
            $this->db->userupnum($userrow['pid'] , http_ip());
            exitjson(-1,'账号或密码错误');
        }
        if($userrow['zt'] != 1){
            exitjson(-1,'您的账号已被封禁 详情请联系站长QQ：'.$this->conf['kfqq']);
        }
        $session=md5($userrow['user'].$userrow['pass'].$this->globalState->get('password_hash').$salt);
        $expiretime=time()+432000;
        $token=aes256auth("{$userrow['user']}\t{$session}\t{$expiretime}",$this->conf->syskey,'ENCODE');
        setcookie("user_token", $token, $expiretime,'/');
        createLog('登录用户中心成功', http_ip(),$userrow['user']);
        $this->db->userupnum($userrow['pid'] , http_ip() , '0',true);
        exitjson(200,'登录成功');
    }
    public function send_reg_code($get , $post){
        if($this->islogin_user == 1 )exitjson(-1,"您已登录");
        if($this->conf->reg_open == 0){
            exitjson(-1,'管理员未开放注册');
        }
        if(!$this->XFCaptcha->XYcaptcha($this->input->captcha))exitjson(-1,'验证码为空或错误！');
        unset($post['captcha']);
        $requiredFields = ['user', 'qq','email'];
        if($this->checkRequiredParams($requiredFields , $post)){
            $this->echomsg('json','用户名、QQ、邮箱不可为空');
        }
        $namedata = [
            'user'=>"用户名重复",
            'qq'=>"QQ重复",
            'email'=>"邮箱重复"
        ];
        foreach ($requiredFields as $k){
            $userrow = $this->db->userrow($post[$k],$k,'pid');
            if($userrow){
                $this->echomsg('json',$namedata[$k]);
            }
        }
        $to = $post['email'];
        
        $row = $this->db->select('regcode', '*', ['to' => $to], [
            'orderBy' => 'id DESC',
            'limit' => 1,
            'single_row' => true
        ])['result'];
        if($row && $row['time'] > time() - 60){
            exitjson(-1, "两次发送短信之间需要相隔60秒！");
        }
        $count = $this->db->select('regcode', 'COUNT(*) as count', [
            'to' => $to,
            'time' => ['operator' => 'gt', 'value' => time() - 3600 * 24]
        ],['single_row'=>true])['result']['count'];
        
        if ($count > 6) {
            exitjson(-1, "发送次数过多，请更换收信方式！");
        }
        $count = $this->db->select('regcode', 'COUNT(*) as count', [
            'ip' => http_ip(),
            'time' => ['operator' => 'gt', 'value' => time() - 3600 * 24]
        ],['single_row'=>true])['result']['count'];
        if ($count > 10) {
            exitjson(-1, "你今天发送次数过多，已被禁止发信");
        }
        $code = rand(111111, 999999);
        $sub = $this->conf['sitename'] . ' - 验证码获取';
        $msg = $this->MsgNotice->send('code','用户',['code'=>$code]);
        $sms_auth = send_mail($to, $sub, $msg);
        if($sms_auth){
            $insertData = [
                'type' => '2',
                'code' => $code,
                'to' => $to,
                'time' => time(),
                'ip' => http_ip(),
                'status' => '0'
            ];
            if ($this->db->insert('regcode', $insertData)) {
                $_SESSION['send_mail'] = time();
                exitjson(200, "验证码发送成功");
            } else {
                exitjson(-1, "验证码写入失败");
            }
        }
        exitjson(-1, "验证码发送失败");
        
        
    }
    public function reg($get , $post , $data){
        $data = array_merge($post , $data);
        if($this->islogin_user == 1 )exitjson(-1,"您已登录");
        if(!$this->XFCaptcha->XYcaptcha($this->input->img_code))exitjson(-1,'验证码为空或错误！');
        unset($data['img_code']);
        
        $requiredFields = ['user', 'qq','email','code','pass'];
        
        if($this->checkRequiredParams($requiredFields , $data)){
            $this->echomsg('json','所有内容不可为空！');
        }
        $namedata = [
            'user'=>"用户名重复",
            'qq'=>"QQ重复",
            'email'=>"邮箱重复"
        ];
        foreach ($namedata as $k=>$v){
            $userrow = $this->db->userrow($data[$k],$k,'pid');
            if($userrow){
                $this->echomsg('json',$v);
            }
        }
        
        if(strlen($data['pass']) < 6){
            exitjson(500, "密码长度不能少于6位");
        }
        if(ctype_digit($data['pass'])){
            exitjson(500, "密码过于简单，请使用包含字母、数字和特殊字符的更复杂密码");
        }
        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            exitjson(500, "邮箱格式不正确");
        }
        if (!empty($data['user']) && preg_match("/[\x{4e00}-\x{9fa5}]+/u", $data['user'])) {
            exitjson(500, "用户名不能包含中文字符");
        }
        $result = $this->db->select('regcode', '*', [
            'to' => $data['email'],
            'code' => $data['code'],
            'type' => 2
        ], [
            'orderBy' => 'id DESC',
            'limit' => 1,
            'single_row' => true
        ])['result'];
        if(!$result){
            exitjson(-1,'验证码不正确！');
        }
        if($result['time']<time()-300 || $result['status']==1){
            exitjson(-1,'验证码已失效，请重新获取!');
        }
        unset($data['code']);
        $salt = $this->salt;
        $data['pass'] = md5($salt . md5($salt.$data['pass'].$salt.md5($salt.$data['pass'].$salt).$data['pass'].$salt) . $salt);
        $data['pay_pass'] = md5(md5($data['pass']));
        $arr = [
          'pid'=>'1'.mt_rand(10000000,99999999),
          'key'=>md5(randpw(11) . $data['qq']),
          'salt'=>$salt,
          'addtime'=>$this->date,
          'money'=>$this->conf->reg_money ?: '0.00',
          'INPUTFREE'=>3,
          'outtime'=>180,
          'username'=>$this->conf->sitename . '商户',
        ];
        if($this->conf->user_vip > 0){
            $vipdata = ['alipay','wxpay','qqpay'];
            $time = date("Y-m-d H:i:s", strtotime("+{$this->conf['user_vip']}days"));
            foreach ($vipdata as $vip){
                $arr[$vip . '_free_vip_time'] = $time;
            }
        }
        $params = array_merge($arr , $data);
        if($this->conf->reg_pay == 1){
            $token  = aes256auth(json_encode($params) , SYS_KEY);
            $this->db->update('regcode', 
                ['status' => '1'], 
                ['id' => $result['id']]
            );
            $typedata = ['alipay'=>'支付宝','qqpay'=>'QQ钱包','wxpay'=>'微信支付','usdt'=>"USDT"];
            foreach ($typedata as $k =>$v){
                $count = $this->db->select('qrlist', 'COUNT(*) as count', [
                    'type' => $k,
                    'pid' =>$this->conf->zero_pid,
                    'status'=>1
                ],['single_row'=>true])['result']['count'];
                if($count <=0){
                    unset($typedata[$k]);
                }
            }
            exitjson(1,'success',['money'=>$this->conf->reg_pay_price ,'token'=>$token ,'pay_type'=>$typedata]);
            
        }else{
            
            if($this->db->insert('user',$params)){
                $this->db->update('regcode', 
                    ['status' => '1'], 
                    ['id' => $result['id']]
                );
                $sub = $this->conf['sitename'] . ' - 商户注册成功提醒';
                $msg = $this->MsgNotice->send('reg',$this->conf->sitename . '用户',$params);
                send_mail($params['email'], $sub, $msg);
                exitjson(200,'注册成功');
            }
           
        }
        exitjson(-1,'注册失败');
    }
    public function Retrieve(){
        if($this->islogin_user == 1 )exitjson(-1,"您已登录");
        $user = $this->input->account;
        $data = ['user', 'email', 'phone','qq'];
        $conditions = [];
        $params = [];
        
        foreach ($data as $key) {
            $conditions[] = "`$key` = :user";
        }
        $sql = "SELECT `email`,`pid`,`user` FROM `pre_user` WHERE " . implode(' OR ', $conditions) . " LIMIT 1";
        $params = ['user' => $user];
        $userrow = safeSqlQuery($sql, $params,'select',['single_row'=>true])['result'];
        if(empty($userrow)){
            exitjson(-1,'账号不存在！');
        }
        $userrow['time'] = time();
        $token = aes256auth(json_encode($userrow) , SYS_KEY);
        
        $url = $this->httphost . 'index/Retrieve?token='.$token;
        if($_SESSION['send_Retrieve'] > time() - 3600 * 24){
            exitjson(-1,'一天仅允许重置一次密码');
        }
        $sub = $this->conf['sitename'] . ' - 密码重置';
        $msg = $this->MsgNotice->send('Retrieve',$userrow['user'],$url);
        if(send_mail($userrow['email'], $sub, $msg)){
            $_SESSION['send_Retrieve'] = time();
            exitjson(200,'success');
        }
        
        exitjson(-1,'发送失败！');
        
    }
    public function ordergetDataList($get){
        if($this->islogin_user != 1 )exitjson(-1,"请先登录");
        
        $params = ['trade_no', 'out_trade_no', 'qr_id', 'name','money','type'];
        $name  = $get['name'];
        $value = $get['value'];
        $where = ['pid'=>$this->uid];
        if(!empty($name) && in_array($name, $params) && $value !== false){
            $where[$name] = $value;
        }
        $getCount = $this->db->select("order","count(*) as count",$where,['single_row' => true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("order","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        foreach ($data as &$res){
            $res['typename'] = pay_type($res['type']);
            $res['notify']   = notify_status($res['status'] , $res['notify']). ($res['status'] == 1 && $res['notify'] != 0? '(已通知 '.$res['notify'].'次 )' :'') ;
            $res['statuszh']   = order_status($res['status']);
        }
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function callnotify(){
        if($this->islogin_user != 1 )exitjson(-1,"请先登录");
        $id = $this->input->id;
        if(empty($id))exitjson(-1,'非法操作');
        $row = $this->db->orderrow($id,'id');
        if(empty($row) || $row['pid'] != $this->uid)exitjson(-1,'订单不存在');
        // if($row['status'] != 1)exitjson(-1,'订单尚未支付，无法重新通知！');
        if($row['status'] == 0){
            $res = $this->get_notify($this->E_Type , $row , $this->userrow);
            createLog('手动下发回调 ： '.$row['trade_no'].'',http_ip(),$this->userrow['user']);
        }else{
            $url=creat_callback($row);
            var_dump($url);
            exit;
            $res = do_notify($url['notify'],true);
            $params = [];
            if($row['notify']>0){
                if($res){
                    $params['notify'] = 0;
                }else{
                    $params['notify'] = $row['notify'] + 1;
                    $params['notifytime'] = $this->date;
                }
                $this->db->update('order',$params,['id'=>$id]);
            }
        }
        
        exitjson(200,'补单成功！',['data'=>$res]);
    }
    public function qrlistgetDataList($get){
        if($this->islogin_user != 1 )exitjson(-1,"请先登录");
        $defaultHookType = [0, 2]; // 默认 hook_type
        $defaultType = ['usdt']; // 默认 type

        $where = [
            'pid'=>$this->uid,
            'hook_type'=>[
                'operator'=>'in',
                'value'=>[0,2]
                ],
            'type'=>[
                'operator'=>'notin',
                'value'=>['usdt']
                ],
            ];
        if (isset($get['hook_type'])) {
            $where['hook_type']['value'] = [$get['hook_type']];
        } else {
            $where['hook_type']['value'] = $defaultHookType;
        }
        if (isset($get['type'])) {
            $where['type']['operator'] = 'in';
            $where['type']['value'] = [$get['type']];
        } else {
            $where['type']['value'] = $defaultType;
        }
       
        $getCount = $this->db->select("qrlist","count(*) as count",$where,['single_row' => true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("qrlist","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        foreach ($data as &$res){
            $res['typename'] = pay_type($res['type']);
            $res['cookie_zt'] = cookie_zt($res['status'] , $res['type'] , $res['addtime'] , $res['endtime'] , $res['wx_name'] , $res['hook_type'] , $res['crontime'] , $res['cookie'] , $res['xf_stat'] , $res['xf_type']);
            $res['currentTime'] = (($res['type']=='alipay' && ($res['cookie'] == 'xfqymckxy' || $res['cookie'] == 'xfqydmfxy')) || ($res['type'] == 'wxpay' && $res['hook_type']!=2 && $res['status'] == '1') ) ? date('Y-m-d H:i:s', time()) : date('Y-m-d H:i:s', $res['crontime']);
            $res['beizhu'] = $res['beizhu']?$res['beizhu']:"无";
        }
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function typevipgetDataList(){
        if($this->islogin_user != 1 )exitjson(-1,"请先登录");
        $data = [];
        $typedata = ['alipay','wxpay','qqpay'];
        
        foreach ($typedata as $type){
            $status = $this->userrow[$type.'_free_vip_time'] > $this->date;
            $data[] =  [
                'type'=>$type,
                'type_name'=>pay_type($type,true),
                'status'=>$status ? 1 : 0,
                'expire_time'=>$status ? $this->userrow[$type.'_free_vip_time'] : '未开通或已过期'
            ];
        }
        exitjson(0,'success',['count'=>count($typedata),'data'=>$data]);
    }
    public function packagesgetDataList(){
        if($this->islogin_user != 1 )exitjson(-1,"请先登录");
        $where = ['status'=>1];
        $result = $this->db->select("package","*",$where,['orderBy'=>'id ASC']);
        $data = $result['result'];
        exitjson(200,'ok',array('data'=>$data));
    }
    public function workgetDataList($get){
        if($this->islogin_user != 1 )exitjson(-1,"请先登录");
        $where = ['uid'=>$this->uid];
        $getCount = $this->db->select("work","count(*) as count",$where,['single_row' => true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("work","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        foreach($data as &$res){
            $res['status'] = $res['active'] == 1 ? '已完结':'待处理';
        }
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function PlugingetDataList($get){
        if($this->islogin_user != 1 )exitjson(-1,"请先登录");
        $where = [];
        $getCount = $this->db->select("down","count(*) as count",$where,['single_row' => true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("down","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
}

?>